package server

import (
	"database/sql"

	_ "github.com/go-sql-driver/mysql"
)

var (
	DB_DRIVER   = "mysql"
	DB_USER     = "isee"
	DB_PASSWORD = "123456"
	DB_NAME     = "isee"
	DB_CHARSET  = "utf8"
)

type confSocket struct {
	uid string
	tid string
	sid string
}

func (conf *confSocket) Get() (*addressConf, string, error) {
	db, err := sql.Open(DB_DRIVER, DB_USER+":"+DB_PASSWORD+"@/"+DB_NAME+"?charset="+DB_CHARSET)
	if err != nil {
		return nil, "", err
	}
	defer db.Close()

	var address addressConf

	err = db.QueryRow("select ip,port from address where id=? and uid=?",
		conf.sid, conf.uid).Scan(&address.ip, &address.port)
	if err != nil {
		return nil, "", err
	}
	var template string
	err = db.QueryRow("select content from template where id=? and uid=?",
		conf.tid, conf.uid).Scan(&template)
	if err != nil {
		return nil, "", err
	}
	return &address, template, nil
}

func (conf *confSocket) GetAddress() (*addressConf, error) {
	db, err := sql.Open(DB_DRIVER, DB_USER+":"+DB_PASSWORD+"@/"+DB_NAME+"?charset="+DB_CHARSET)
	if err != nil {
		return nil, err
	}
	defer db.Close()

	var address addressConf

	err = db.QueryRow("select name,ip,port from address where id=? and uid=?",
		conf.sid, conf.uid).Scan(&address.name, &address.ip, &address.port)
	if err != nil {
		return nil, err
	}

	return &address, nil
}
